//index.js
const app = getApp()
const request = require('../../utils/request.js')
const buryDataStep = require('../../utils/buryDataStep.js');

Page({
  data: {
    appIds: [],
    appIdsUp: [],
    appIdsDown: [],
    jumpedAppIds: [],
    currentIndex: 0,
    openAnotherMiniProgramStart: 0,
    isOpenAnotherMiniProgram: false,
    openAnotherMiniProgramEnd: 0,
    isShareGetStepsShow: false,
    isShareGetMoreStepsShow: false,
    isStartCalculateWacthAdTime: false,
    wacthAdTimeBegin: 0,
    isAddMiniProgramShow: false,
    isGetStepByWatchAdShow: false,
    isGetStepByWatchAdStart: false,
    getStepByWatchAdTimeBegin: 0
  },

  get_step_by_play: function(event) {
    let index = event.target.id;
    if(this.data.appIds[index].app_id === "wxc3087d539fadc0a0"){
      console.log('打开添加到小程序指南');
      this.setData({
        isAddMiniProgramShow: true
      });
    }else if(this.data.appIds[index].app_id === "1"){
      this.setData({
        isGetStepByWatchAdShow: true,
        isGetStepByWatchAdStart: true
      });
    }else{
      this.setData({
        currentIndex: index
      });
      this.openAnotherMiniProgram();

      // 数据埋点--> 点击小程序
      request.dataBuried(buryDataStep.earn_click, 'earn_click', app.globalData.openId);
    }
  },

  // 打开一个小程序
  openAnotherMiniProgram: function() {
    wx.navigateToMiniProgram({
      appId: this.data.appIds[this.data.currentIndex].app_id,
      success: res => {

        // 必须打开一个上线的小程序 该函数才执行
        this.data.openAnotherMiniProgramStart = new Date().getTime();
        this.setData({
          isOpenAnotherMiniProgram: true
        });

        console.log('用户成功打开另外一个小程序！')
        // 数据埋点--> 观看小程序成功
        request.dataBuried(buryDataStep.earn_succ, 'earn_succ', app.globalData.openId);
      }
    })
  },

  onShow: function() {
    console.log('onshow xxx', this.data.isOpenAnotherMiniProgram)
    // 判断是否打开看广告的步数
    if (this.data.isGetStepByWatchAdStart && new Date().getTime() - this.data.getStepByWatchAdTimeBegin > 15000){
      this.setData({
        isGetStepByWatchAdStart: false,
        isGetStepByWatchAdShow: false,
      });

      //提醒获得1000步
      this.showWithdrawFail('获得1000步看广告奖励哦！')
      // 调用后端函数
      this.toGetStepByWatchAdSuccess();

    }
    
    // 判断红包界面，看广告时长
    if (this.data.isStartCalculateWacthAdTime && new Date().getTime() - this.data.wacthAdTimeBegin > 5000) {
      this.setData({
        isStartCalculateWacthAdTime: false,
        isShareGetStepsShow: false,
        isShareGetMoreStepsShow: true
      });

      // 2000 steps
      this.toGetMoreStep();
    }

    if (this.data.isOpenAnotherMiniProgram) {
      this.data.openAnotherMiniProgramEnd = new Date().getTime();
      let playTimes = this.data.openAnotherMiniProgramEnd - this.data.openAnotherMiniProgramStart;

      // isOpenANoterMiniProgram 是为了告诉onshow 你得计算一下时长，计算结束别忘记设置会false
      this.setData({
        isOpenAnotherMiniProgram: false,
      });
      this.isObtainAward(playTimes, this.data.currentIndex);
    }

    // 获取数据
    this.getData();

    // 数据埋点--> 显示赚步数页面
    request.dataBuried(buryDataStep.earn_show, 'earn_show', app.globalData.openId);
  },


  // 提示框
  showWithdrawFail: function (msg) {
    wx.showToast({
      title: msg,
      icon: "none",
      duration: 1500
    })
  },

  // 判断数组是否有
  isInThisArray(appId, JumpedList){
    for(let i=0; i<JumpedList.length; i++){
      if(appId == JumpedList[i]){
        return true;
      }
    }
    return false;
  },

  //判断是否获得奖励
  isObtainAward: function(playTimes, index) {
    if (playTimes > 15000) {
      this.setData({
        isShareGetStepsShow: true,
        isStartCalculateWacthAdTime: true
      });
    
      // 数据埋点--> 显示获得运动步数弹窗
      request.dataBuried(buryDataStep.earn_share_show, 'earn_share_show', app.globalData.openId);
    } else {
      wx.showModal({
        content: '哎呀，观看时间少于15秒，是否重新观看？',
        cancelText: '算了',
        confirmText: '重新观看',
        success: res => {
          if (res.confirm) {
            this.openAnotherMiniProgram(this.data.appIds[this.data.currentIndex].app_id);
          }
        },
      })
    }
  },
  
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      this.setData({
        isShareGetMoreStepsShow: false
      });
      
      return this.shareMessage();

      // 数据埋点--> 点击更多步数
      request.dataBuried(buryDataStep.earn_share_click2, 'earn_share_click2', app.globalData.openId);
    } else if (res.from === 'menu'){
      return this.shareMessage();

      // 数据埋点--> 点击分享menu
      request.dataBuried(buryDataStep.share_click, 'share_click', app.globalData.openId);     
    }
  },

  // share
  shareMessage: function(){
    let url = "/pages/index/index?from_open_id=" + this.data.myOpenId
    let title = app.globalData.userInfo.nickName + "@你，【运动步数能赚钱】你还不知道吗？"
    return {
      title: title,
      imageUrl: "/images/publicize_3.jpg",
      path: url,
    }
  },

  //toGetMoreStep
  toGetMoreStep: function() {
    console.log('增加步数2000');
    request.getRewardStep(this.data.appIds[this.data.currentIndex].app_id, true).then(res => {
      console.log(res)
    })
  },

  //toGetStepByWatchAdSuccess
  toGetStepByWatchAdSuccess: function () {
    console.log('增加步数1000');
    request.getAdRewardStep(6, false).then(res => {
      console.log(res)
    })

    this.getData();
  },


  //closeGetStepShow
  closeGetStepShow: function() {
    this.setData({
      isShareGetStepsShow: false,
      isStartCalculateWacthAdTime: false,
    })

    console.log('closeGetStepShow，增加步数1000');
    request.getRewardStep(this.data.appIds[this.data.currentIndex].app_id, false).then(res => {
      console.log(res)
    })

    this.getData();
  },

 
  //closeGetMoreStepShow
  closeGetMoreStepShow: function() {
    this.setData({
      isShareGetMoreStepsShow: false
    })    
  },

  //刷新页面数据
  getData: function(){
    request.getJumpedAppIds().then(res => {
      let Jumped = [];
      let notJumped = [];
      for (let i = 0; i < res.app_list.length; i++) {
        let appId = res.app_list[i];
        if(this.isInThisArray(appId.app_id, res.jumped_list) || (appId.app_id === "1" && res.data.today_ad_times > 4)){
          appId.isJumped = true;
          Jumped.push(i);
        }else {
          appId.isJumped = false;
          notJumped.push(i);
        }
      }

      // 已完成的排序在后面
      notJumped = notJumped.concat(Jumped);
      console.log('notJumped+ Jumped', notJumped);
      let miniProgramData = [];
      for (let i in notJumped) {
        miniProgramData.push(res.app_list[notJumped[i]]);
      }
      
      // 为了让广告在中间，分开两次循环
      let appIdsUpLastIndex = miniProgramData.length > 1 ? 2 : miniProgramData.length;

      this.setData({
        appIds: miniProgramData,
        appIdsUp: miniProgramData.slice(0, appIdsUpLastIndex),
        appIdsDown: miniProgramData.slice(appIdsUpLastIndex, miniProgramData.length),
        jumpedAppIds: res.jumped_list
      })
    })
  },

  // 广告打开成功的回调
  onHide: function(){
    if(this.data.isStartCalculateWacthAdTime){
      this.setData({
        wacthAdTimeBegin: new Date().getTime()
      });
    }

    if (this.data.isGetStepByWatchAdStart) {
      this.setData({
        getStepByWatchAdTimeBegin: new Date().getTime()
      });
    }
  },

  // 关闭添加小程序指南
  closeMiniProgramGuide: function(){
    this.setData({
      isAddMiniProgramShow: false
    });

    // isCloseMiniProgramGuide
    let key = wx.getStorageSync('isCloseMiniProgramGuide');
    if (!key) {
      key = true;
      wx.setStorageSync('isCloseMiniProgramGuide', key);
    }
  },

  // 关闭看看广告得步数页面
  closeGetStepByWatchAd: function(){
    this.setData({
      isGetStepByWatchAdShow: false
    });
  }

})